<template>
  <a-table
    bordered
    :pagination="false"
    row-key="frontKey"
    :columns="columns"
    :data-source="keywordTable"
    :loading="loading"
    :scroll="{ y: 860 }"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'clientType'">
        {{ PlatformKeyMap[record.clientType] }}
      </template>
      <template v-else-if="column.key === 'reasons'">
        <div class="cell-wrapper">
          <template v-if="record.reasons.length">
            <a-tag class="mt-2 first-0" color="orange" :key="index" v-for="(reason, index) in record.reasons">
              {{ reason }}
            </a-tag>
          </template>
          <span v-else>--</span>
        </div>
      </template>
      <template v-if="column.key === 'operate'">
        <div>
          <a-button
            type="primary"
            :disabled="record.disabled || record.selected || record.isSold"
            @click="handleKeywordSelect(record)"
          >
            <div v-if="record.disabled">禁止售卖</div>
            <div v-else-if="record.selected">
              已选择
              <arrow-right-outlined />
            </div>
            <div v-else-if="record.isSold">已售出</div>
            <div v-else>
              预选
              <arrow-right-outlined />
            </div>
          </a-button>
        </div>
      </template>
      <template v-if="column.key === 'isSoldArea'">
        <area-popover ellipsis :areas="record.isSoldArea" />
      </template>
    </template>
  </a-table>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import { ArrowRightOutlined } from '@ant-design/icons-vue'
import { message, type TableProps } from 'ant-design-vue'
import { cloneDeep } from 'lodash-es'
import { useVModel } from '@vueuse/core'
import is from '@/utils/is'
import getKeywordCheckResult from '@/services/price-sheet/getKeywordCheckResult'
import getPhoenixCheckResult from '@/services/price-sheet/getPhoenixCheckResult'
import type { PriceKeyword } from '@/core/interfaces/keyword'
import { PlatformKeyMap } from '@/core/mapper/platform'
import { PhoenixPlatformEnum, PhoenixSold, PlatformEnum } from '@/core/enums/platform'
import { mapClientTypeToPhoenix } from '@/shared'
import { ProductEnum } from '@/core/enums/platform'

interface Props {
  loading: boolean
  maxLength?: number
  keywordTableData: PriceKeyword[]
  selectedTableData: PriceKeyword[]
  type: ProductEnum
  comboId: number
  currentPackage?: Object
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  selectedTableData: () => [],
  keywordTableData: () => []
})

const selectedTable = useVModel(props, 'selectedTableData')
const keywordTable = useVModel(props, 'keywordTableData')
const [, fetchKeywordCheckResult] = getKeywordCheckResult()
const [, fetchPhoenixCheckResult] = getPhoenixCheckResult()

const columns: TableProps['columns'] = [
  {
    title: '推荐关键词',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '端口',
    dataIndex: 'clientType',
    key: 'clientType',
    filters: [
      { text: PlatformKeyMap[PlatformEnum.PC], value: PlatformEnum.PC },
      { text: PlatformKeyMap[PlatformEnum.MOBILE], value: PlatformEnum.MOBILE }
    ],
    onFilter: (value, record: PriceKeyword) => record.clientType === value
  },
  ...(props.type === ProductEnum.BWSD || props.type === ProductEnum.BWSDYXB
    ? [
        {
          title: '热度',
          dataIndex: 'heatRate',
          key: 'heatRate',
          width: '100px'
        }
      ]
    : []),
  ...(props.type === ProductEnum.BWSD || props.type === ProductEnum.BWSDYXB
    ? [
        {
          title: '已售区域',
          dataIndex: 'isSoldArea',
          key: 'isSoldArea'
        }
      ]
    : []),
  {
    title: '操作',
    dataIndex: 'operate',
    key: 'operate',
    width: '100px'
  }
]

async function handleKeywordSelect(record: PriceKeyword) {
  if (record.loading) {
    return
  }
  if (props.currentPackage && (props.currentPackage.productId === 12 || props.currentPackage.productId === 13)) {
    let maxHeat
    //校验热度是否超过
    //pc端
    if (
      props.currentPackage.id === 24 ||
      props.currentPackage.id === 29 ||
      props.currentPackage.id === 27 ||
      props.currentPackage.id === 32
    ) {
      maxHeat = props.currentPackage.pcHeatLimit
    }
    //移动端
    if (
      props.currentPackage.id === 25 ||
      props.currentPackage.id === 30 ||
      props.currentPackage.id === 28 ||
      props.currentPackage.id === 33
    ) {
      maxHeat = props.currentPackage.wapHeatLimit
    }
    if (record.heatRate + totalHeatRate.value > maxHeat) {
      message.error('您选择的关键词热度过高，将超出当前套餐最大热度')
      return
    }
    //双端
    if (props.currentPackage.id === 26 || props.currentPackage.id === 31) {
      if (isPcHeatExceeded(record.heatRate) && record.clientType === 0) {
        message.error('您选择的关键词热度过高，PC端将超出套餐热度')
        return
      }
      if (isWapHeatExceeded(record.heatRate) && record.clientType === 1) {
        message.error('您选择的关键词热度过高，移动端将超出套餐热度')
        return
      }
    }
  } else {
    if (is.number(props.maxLength) && props.maxLength === props.selectedTableData.length) {
      message.error('您选择的关键词数量已到最大上限')
      return
    }
  }

  record.loading = true

  const [err1, residtem] = await fetchKeywordCheckResult({
    keyword: record.name,
    clientType: record.clientType,
    productId: localStorage.getItem('newproductId'),
    comboId: props.comboId
  })
  // const [err2, res2] = await fetchPhoenixCheckResult({
  //   keyword: record.name,
  //   device: mapClientTypeToPhoenix(record.clientType) as PhoenixPlatformEnum
  // })

  record.loading = false
  const idis = localStorage.getItem('productId')
  if (residtem != undefined) {
    if (residtem.data.code === 0 && idis != 2) {
      record.selected = true
      selectedTable.value.unshift(cloneDeep(record))
    } else {
      if (!err1) {
        record.selected = true
        selectedTable.value.unshift(cloneDeep(record))
      } else {
        message.error('关键词已售出，无法继续添加')
      }
    }
  }

  // if (!err1 && !err2 && res2.data.data?.sold === PhoenixSold.unsold) {
  //   record.selected = true
  //   selectedTable.value.unshift(cloneDeep(record))
  // } else {
  //   message.error('关键词已售出，无法继续添加')
  // }
}

const totalHeatRate = computed(() => {
  return props.selectedTableData.reduce((sum, item) => sum + Number(item.heatRate || 0), 0)
})

// 计算 PC 和 WAP 的当前热度
const pcHeat = computed(() => {
  return props.selectedTableData
    .filter((item) => item.clientType === 0)
    .reduce((sum, item) => sum + (item.heatRate || 0), 0)
})

const wapHeat = computed(() => {
  return props.selectedTableData
    .filter((item) => item.clientType === 1)
    .reduce((sum, item) => sum + (item.heatRate || 0), 0)
})

// 校验 PC 热度是否超限
const isPcHeatExceeded = (heatRate) => {
  if (!props.currentPackage || (props.currentPackage.id !== 26 && props.currentPackage.id !== 31)) return false
  return heatRate + pcHeat.value > (props.currentPackage.pcHeatLimit || 0)
}

// 校验 WAP 热度是否超限
const isWapHeatExceeded = (heatRate) => {
  if (!props.currentPackage || (props.currentPackage.id !== 26 && props.currentPackage.id !== 31)) return false
  return heatRate + wapHeat.value > (props.currentPackage.wapHeatLimit || 0)
}
</script>

<style lang="scss" scoped>
.first-0 {
  &:first-child {
    margin-top: 0;
  }
}
</style>
